package com.spdzen.controller.admin;

import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.spdzen.support.AESUtils;
import com.spdzen.support.AdminLoginUtils;
import com.spdzen.support.LogUtils;
import com.spdzen.support.VerificationCodeUtils;
import com.spdzen.support.result.BaseResultCode;
import com.spdzen.support.result.JsonResult;

@Controller
@RequestMapping("/admin")
public class AuthAdminController {
	private static final String SESSION_LOGIN_CODE = "ADMIN_LOGIN_CODE";
	
	@RequestMapping(path = { "/getCurrentUser.do" })
	@ResponseBody
	public JsonResult getCurrentUser() {
		return JsonResult.success(AdminLoginUtils.getLoginInfo());
	}

	@RequestMapping(path = { "/login.do" }, method = { RequestMethod.GET })
	public String loginPageView(HttpServletRequest request) {
		return "/admin/login";
	}

	@RequestMapping(path = { "/login.do" }, method = { RequestMethod.POST })
	@ResponseBody
	public JsonResult login(String ut, HttpServletRequest request, HttpSession session) {
		String scode = (String) session.getAttribute(SESSION_LOGIN_CODE);
		session.removeAttribute(SESSION_LOGIN_CODE);

		if (StringUtils.isBlank(ut)) {
			return JsonResult.error("用户名不存在或密码错误！");
		}

		if (StringUtils.isBlank(scode)) {
			return JsonResult.error("验证码错误！");
		}

		try {
			String jsonstr = AESUtils.decrypt(ut);
			JSONObject json = JSON.parseObject(jsonstr);

			String loginName = json.getString("u");
			String password = json.getString("p");
			String code = json.getString("c");

			if (StringUtils.isBlank(loginName) || StringUtils.isBlank(password)) {
				return JsonResult.error("用户名不存在或密码错误！");
			}

			if (StringUtils.isBlank(code) || !code.trim().equalsIgnoreCase(scode)) {
				return JsonResult.error("验证码错误！");
			}

			Subject subject = SecurityUtils.getSubject();
			AuthenticationToken token = new UsernamePasswordToken(loginName, password, false);
			subject.login(token);

			if (subject.isAuthenticated()) {
				return JsonResult.success();
			} else {
				return JsonResult.error("用户名不存在或密码错误！");
			}
		} catch (AuthenticationException e) {
			return JsonResult.error("用户名不存在或密码错误！");
		} catch (Exception e) {
			LogUtils.getLogger().error(ut, e);
			return JsonResult.error();
		}
	}

	@RequestMapping("/logout.do")
	public String logout(HttpServletRequest request) {
		try {
			Subject subject = SecurityUtils.getSubject();
			subject.logout();
			AdminLoginUtils.removeLoginInfo();
		} catch (Exception e) {
			LogUtils.getLogger().error("", e);
		}

		return "redirect:/admin/login.do";
	}

	@RequestMapping("/login/proxy.do")
	public String loginProxy(HttpServletRequest request) {
		return "/admin/loginProxy";
	}

	@RequestMapping("/login/code.do")
	public void loginCode(Integer width, Integer height, HttpServletRequest request, HttpServletResponse response) {
		if (width == null || width.intValue() < 1) {
			width = VerificationCodeUtils.DEFAULT_IMAGE_WIDTH;
		}

		if (height == null || height.intValue() < 1) {
			height = VerificationCodeUtils.DEFAULT_IMAGE_HEIGHT;
		}

		response.setContentType("image/jpeg");
		try {
			OutputStream os = response.getOutputStream();
			String code = VerificationCodeUtils.randomString();
			request.getSession().setAttribute(SESSION_LOGIN_CODE, code);
			VerificationCodeUtils.write(code, width, height, os);
		} catch (Exception e) {
			LogUtils.getLogger().error("", e);
		}
	}

	@RequestMapping("/unauthorized.do")
	@ResponseBody
	public JsonResult unauthorized(HttpServletRequest request) {
		return new JsonResult(BaseResultCode.UNAUTHORIZED);
	}
}
